package com.lagou.consumer;

import com.lagou.client.UserClientHandler;
import com.lagou.entity.RpcRequest;
import com.lagou.server.JSONSerializer;
import com.lagou.server.RpcDecoder;
import com.lagou.server.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author sxnan
 * @className RpcConsumer
 * @description TODO
 * @date 2020/8/18
 */
public class RpcConsumer {
    //创建一个线程池对象，处理自定义事件
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    //声明一个自定义的事件处理器
    private static UserClientHandler client;

    /*** 初始化客户端 */
    private static void initClient() {
        //初始化UserClientHandler
        client = new UserClientHandler();
        //创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //创建客户端的引导对象
        Bootstrap b = new Bootstrap();
        //配置启动引导对象
        b.group(group)
                //设置通道启动类型为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                //监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                //获取ChannelPipeline
                ChannelPipeline p = ch.pipeline();
                //设置编码
                p.addLast(new StringDecoder());
                p.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                //添加自定义事件处理器
                p.addLast(client);
            }
        });
        try {
            //绑定端口
            b.connect("localhost", 8991).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /*** 创建一个代理对象 */
    public static Object createProxy(final Class<?> serviceClass, final RpcRequest param) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, (proxy, method, args) -> {
            if (client == null) {
                initClient();
            }// 设置参数
            client.setPara(param);
            return executor.submit(client).get();
        });
    }
}